package easycontroller.plugin.expand;


import easycontroller.plugin.Plugin;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class H2Plugin extends Plugin {

    private String root;

    {
        setName("h2");
    }

    static {
        try {
            Class.forName("org.h2.Driver");
        } catch (ClassNotFoundException ignore) {
        }
    }

    public String getDescription() {
        return "提供h2数据库相关操作。\n" +
                "使用getConnection(String,String,String)或getConnection(String)获取数据库连接";
    }

    @Override
    public void start() {

        if (config != null) {
            root = config.get("db.root");
        }

        if (root == null) {
            Properties properties = System.getProperties();
            root = properties.getProperty("user.home") + File.separator + ".h2";
            System.out.println("h2插件根路径:" + root);
        }
    }

    @Override
    public void stop() {
    }

    @Override
    public void restart() {
        start();
    }

    private List<Connection> connections = new ArrayList<Connection>();

    public Connection getConnection(String name, String username, String password) {
        try {
            return DriverManager.getConnection("jdbc:h2:" + root + File.separator + name, username, password);
        } catch (SQLException e) {
            return null;
        }
    }

    public Connection getConnection(String name) {
        try {
            return DriverManager.getConnection("jdbc:h2:" + root + File.separator + name);
        } catch (SQLException e) {
            return null;
        }
    }

}
